<?php

namespace app\admin\controller;

use app\model\Notice as noticeModel;
use app\common\controller\Adminbase;

class Notice extends Adminbase
{

    public function index()
    {
        $model = 'Notice';

        if ($this->request->isAjax()) {
            $map = $this->buildParamsMap();

            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list = noticeModel::where($map)
                ->field('id, type, title, status, create_time, update_time, sort')
                ->withAttr('type', function ($value) {
                    return $value ? noticeModel::TYPES[$value] : '';
                })
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->select();
            $total = noticeModel::where($map)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDataUrl()
            ->setFormUrl('form')
            ->setSwitchTpl('switchTpl', 'status')
            ->setModel($model)
            ->setLimit()
            ->addTableCheckBox()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('type', '所属类型')
            ->addTableColumn('title', '公告标题')
            ->addTableColumn('create_time', '创建时间')
            ->addTableColumn('create_time', '更新时间')
            ->addTableColumn('sort', '排序', null, null, false, '', false, '', true)
            ->addTableColumn('status', '状态', null, '#switchTpl', false, '', false)
            ->addTableOperation()
            ->returnForm();

        $this->assign('is_verify', 0);
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $model = 'Notice';

        $id = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = NoticeModel::get($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $info = [
                'type' => 1,
                'sort' => 50,
            ];
        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('type', 'radio', '所属类型', '', noticeModel::TYPES, 1)
            ->addFormItem('title', 'text', '公告标题', '', [], 1)
            ->addFormItem('content', 'textarea', '内容', '', [], 1)
            ->addFormItem('sort', 'number', '排序', '值越小排序越靠前')
            ->setFormData($info)
            ->returnForm();

        $this->assign('is_verify', 0);
        $this->assign('module', 'app');
        return $this->fetch('admin@common/form');
    }

}
